﻿using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using Castle.Windsor;

namespace Hiver.WebApi.Installers
{
    /// <summary>
    /// WebAPI路由注册
    /// </summary>
    public class WindsorCompositionRoot : IHttpControllerActivator
    {
        /// <summary>
        /// 注册容器
        /// </summary>
        private readonly IWindsorContainer _container;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="container"></param>
        public WindsorCompositionRoot(IWindsorContainer container)
        {
            this._container = container;
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="request"></param>
        /// <param name="controllerDescriptor"></param>
        /// <param name="controllerType"></param>
        /// <returns></returns>
        public IHttpController Create(
            HttpRequestMessage request,
            HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {
            var controller =
                (IHttpController)this._container.Resolve(controllerType);

            request.RegisterForDispose(
                new Release(
                    () => this._container.Release(controller)));

            return controller;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private class Release : IDisposable
        {
            private readonly Action _release;

            public Release(Action release)
            {
                this._release = release;
            }

            public void Dispose()
            {
                this._release();
            }
        }
    }
}